package com.sywl.ytcx.Interceptor.handler;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.regex.Pattern;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class IndexInterceptor implements HandlerInterceptor {
    private static final Pattern IPV4_PATTERN = Pattern.compile(
        "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取客户端 IPv4 地址
        String clientIp = getClientIPv4Address(request);
        // 获取访问路径
        String requestUri = request.getRequestURI();
        System.out.println("ip：" + clientIp);
        System.out.println("访问路径：" + requestUri);
        System.out.println("访问时间：" + new Date());
        System.out.println("========================");
        return true; // 放行请求
    }

    /**
     * 获取客户端的 IPv4 地址，考虑了代理服务器的情况
     * @param request HttpServletRequest 对象
     * @return 客户端的 IPv4 地址，如果未找到则返回 null
     */
    private String getClientIPv4Address(HttpServletRequest request) {
        String[] headers = { "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR" };
        for (String header : headers) {
            String ipList = request.getHeader(header);
            if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
                String[] ips = ipList.split(",");
                for (String ip : ips) {
                    if (isValidIPv4(ip.trim())) {
                        return ip.trim();
                    }
                }
            }
        }
        String remoteAddr = request.getRemoteAddr();
        if (isValidIPv4(remoteAddr)) {
            return remoteAddr;
        }
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            return null;
        }
    }

    /**
     * 验证字符串是否为有效的 IPv4 地址
     * @param ip 待验证的 IP 字符串
     * @return 如果是有效的 IPv4 地址返回 true，否则返回 false
     */
    private boolean isValidIPv4(String ip) {
        return IPV4_PATTERN.matcher(ip).matches();
    }
}
